"""
模型模块
存储数据表
auth:@rqy,2021.6.1
"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseAdmin
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save


class BaseModel(models.Model):
    class Meta:
        abstract = True
        ordering = ['-created_time']

    created_time = models.DateTimeField(auto_now_add=True, help_text='创建时间')
    last_modified = models.DateTimeField(auto_now=True, help_text='修改时间')

    def __str__(self):
        raise NotImplementedError


# 分类
class Classify(BaseModel):
    classify = models.CharField(max_length=255, help_text='分类', unique=True)

    def __str__(self):
        return self.classify


# 商品
class Good(BaseModel):
    name = models.CharField(max_length=255, help_text='品名')
    price = models.IntegerField(help_text='价格')
    store = models.IntegerField(help_text='库存')
    classify = models.ForeignKey(to=Classify, blank=True, to_field='classify', null=True, on_delete=models.SET_NULL, help_text='分类')
    types = models.CharField(max_length=255, help_text='属性')
    intro = models.TextField(help_text='介绍')
    p_url = models.URLField(null=True, blank=True, help_text='图片链接')

    def __str__(self):
        return self.name


class GoodRecommend(BaseModel):
    good = models.ForeignKey(to=Good, to_field='id', null=True, on_delete=models.CASCADE, help_text='推荐商品')

    def __str__(self):
        return self.good.name


class HotSale(BaseModel):
    good = models.ForeignKey(to=Good, to_field='id', null=True, on_delete=models.CASCADE, help_text='推荐商品')

    def __str__(self):
        return self.good.name


# 热词首页推荐
class HotWord(BaseModel):
    hot_word = models.CharField(max_length=255, help_text='推荐', unique=True)

    def __str__(self):
        return self.hot_word


# 用户属性
class UserProfile(models.Model):
    # 和User的一对一关系属性，该属性必填.
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # 其他需要存储的属性
    # User因为是Django提供的，如果想要在其上增加一些自己需要的字段和方法，不太好加入，因此UserProfile是达成这个目标的一个有利工具
    SEX_CHOICES = {
        0: 'boy',
        1: 'girl',
    }

    sex = models.SmallIntegerField(default=1, choices=SEX_CHOICES.items(), help_text='性别')
    address = models.CharField(max_length=255, help_text='地址')

    def save(self, *args, **kwargs):
        if not self.pk:
            try:
                p = UserProfile.objects.get(user=self.user)
                self.pk = p.pk
            except UserProfile.DoesNotExist:
                pass

        super(UserProfile, self).save(*args, **kwargs)


# 订单
class Order(BaseModel):
    good = models.ForeignKey(to=Good, to_field='id', on_delete=models.CASCADE, help_text='商品名')
    user = models.ForeignKey(to=User, to_field='id', on_delete=models.CASCADE, help_text='购买者')
    comment = models.TextField(help_text='评价', null=True)

    def __str__(self):
        return str(self.id)


def create_user_profile(sender, instance, created, ** kwargs):
    if created:
        UserProfile.objects.create(user=instance)


class AccountInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'account'


class UserAdmin(BaseAdmin):
    inlines = (AccountInline,)


if __name__ == '__main__':
    ...
else:
    admin.site.unregister(User)
    admin.site.register(User, UserAdmin)

    post_save.connect(create_user_profile, sender=User)
    admin.site.register([Classify, Good, Order, HotWord, GoodRecommend, HotSale])
